package univ.bme.accounting.beans;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import univ.bme.accounting.dao.CommentDAO;
import univ.bme.accounting.domain.Comment;
import univ.bme.accounting.beans.AccountingSessionBean;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor

@ManagedBean
@RequestScoped
public class CommentMB extends MBUtils {

	@EJB
	private CommentDAO commentdao;

	private Comment comment;
	
	@ManagedProperty("#{accountingSessionBean}")
	private AccountingSessionBean accountingSessionBean;
	
	@ManagedProperty("#{transactionMB}")
	private TransactionMB transactionMB;

	public Comment getComment() {
		if(comment == null){
			comment = new Comment();
		}
		return comment;
	}
	
	//Get all entries for the current transaction
	public List<Comment> getAllCommentsForTransaction() {
		return commentdao.findCommentsforTransaction(transactionMB.getTransaction().getId());
	}
	
	public Long getNumberofCommentsForTransaction(int transactionID) {
		return commentdao.getNumberOfCommentsforTransaction(transactionID);
	}
	
	public String createComment(){
		try {
			//Add the user from the session
			comment.setUser(accountingSessionBean.getUser());
			comment.setDate(new Date());
			comment.setTransaction(transactionMB.getTransaction());
			
			//Save the category
			commentdao.save(comment);
			
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		return transactionMB.goToDetails(transactionMB.getTransaction().getId());
	}
}